<template>
  <div class="editAccount">
    <el-dialog :title="account.name"
               :visible.sync="dialogVisible"
               width="920"
               :close-on-click-modal="false"
               @open="openEditAccount"
               :before-close="handleClose">
      <div class="accounts_conditions">
        <el-input :placeholder="$t('custom.attendance.record.search.search')"
                  @input="searchInput"
                  prefix-icon="el-icon-search"
                  v-model="filterText">
        </el-input>
        <el-popover placement="bottom"
                    width="230"
                    @hide="addGroupItemClose"
                    popper-class="manage_accounts_addtemp"
                    v-model="visible">
          <el-form :model="dataForm"
                   :rules="dataRule"
                   :inline="false"
                   ref="addAccount_item"
                   @submit.native.prevent
                   label-width="80px"
                   label-position="top">
            <el-form-item prop="name"
                          :label="$t('custom.reports.name')">
              <el-input :placeholder="$t('custom.mapping.enter')"
                        v-model="dataForm.name">
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary"
                         size="small"
                         v-loading="addLoading"
                         @click="dataFormSubmitHandle(null,false)">{{ $t('custom.workSchedule.template.addBtn') }}</el-button>
            </el-form-item>
          </el-form>
          <div slot="reference"
                v-if="account.modifyFlag"
               class="conditions_ri">
            <img src="../../../../assets/mspbots/mapping/add-circle-plus.png"
                 alt="">
            {{$t('custom.mapping.addAcount')}}
          </div>
        </el-popover>

      </div>
      <div class="accountTree"
           v-loading="accountListLoading">
        <el-tree :data="accountData"
                 :props="defaultProps"
                 ref="treeIn"
                 draggable
                 :filter-node-method="filterNode"
                 :current-node-key="currKey"
                 highlight-current
                 :allow-drop="allowDropTreeLeft"
                  @node-drag-end="handleDragend"
                 default-expand-all
                 node-key="id"
                 @node-click="handleNodeClick">
          <span class="custom-tree-node"
                slot-scope="{ node, data }">
            <span v-if="showAccountToolTilp(node.level,data.label)" class="el-tree-node__label">{{ data.label }}</span>
            <el-tooltip :open-delay="1000" v-else class="item" effect="dark" :content="data.label" placement="top">
              <span class="el-tree-node__label">{{ limitLabelLehgth(data.label,node.level) }}</span>
            </el-tooltip>
            <span class="item_tree_btn_group" v-if="account.modifyFlag">
              <addOrUpdate :title="'edit'"
                           :popData="data"
                           :node="node"
                           @setCurrNodeKey="setCurrNodeKey"
                           @refreshTempList="refreshTempList"
                           @refreshList="init"
                           :visibel="popVisibel"
                           :account="account"></addOrUpdate>
              <addOrUpdate :title="'add'"
                           :popData="data"
                           :node="node"
                           @setCurrNodeKey="setCurrNodeKey"
                           @refreshTempList="refreshTempList"
                           @refreshList="init"
                           :visibel="popVisibel"
                           :account="account"></addOrUpdate>
              <!-- <span class="accounts_btn delete_btn"
                    @click="deleteAccoutGp($event,data)"></span> -->
              <el-popconfirm :title="$t('custom.workSchedule.template.sureDeleteTips')"
                             @confirm="deleteAccoutGp($event,data)"
                             :cancel-button-text="$t('custom.workSchedule.template.cancel')"
                             :confirm-button-text="$t('custom.workSchedule.template.confirm')">
                <span slot="reference"
                      class="accounts_btn delete_btn" v-if="data.children.length===0" ></span>
              </el-popconfirm>
            </span>
          </span>
        </el-tree>
      </div>
      <span slot="footer" class="dialog-footer" v-if="account.modifyFlag">
        <el-button type="primary" @click="saveMappingItemAccount">{{$t('custom.save')}}</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
// import { isIncludeSymbol } from '@/utils/validate'
import addOrUpdate from './add-or-update'
// let id = 1000
export default {
  components: {
    addOrUpdate
  },
  props: {
    account: {
      type: Object,
      default: () => {
        return {
          name: ''
        }
      }
    }
  },
  data () {
    return {
      num: 0,
      popVisibel: '',
      dialogVisible: false,
      filterText: '',
      visible: false,
      accountData: null,
      addLoading: false,
      accountListLoading: false,
      dataForm: { name: '' },
      dataForms: { name: '' },
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      currKey: '',
      flag: true
    }
  },
  computed: {
    dataRule () {
      // var validateSymbol = (rule, value, callback) => {
      //   if (!isIncludeSymbol(value)) {
      //     return callback(new Error(this.$t('validate.isIncludeSymbol')))
      //   }
      //   callback()
      // }
      return {
        name: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur', pattern: '[^ \x22]+' },
          { validator: this.limitNameLength, trigger: 'blur' }
          // { validator: validateSymbol, trigger: 'blur' },
          // { validator: this.validatePass, trigger: 'blur' }
        ]
        // roleIdList: [
        //   { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        // ]
      }
    }
  },
  methods: {
    init () {
      this.getAccountList()
    },
    openEditAccount () {
      this.filterText = ''
      this.getAccountList()
    },
    showAccountToolTilp (level, label) {
      if (label.length + (level - 1) * 2 > 83) return false
      else return true
    },
    limitLabelLehgth (label, level) {
      return label.substring(0, (80 - (level - 1) * 2)) + '...'
    },
    getAccountList () {
      this.accountData = []
      this.accountListLoading = true
      this.$interface.mapping.requstAccountList({ accountId: this.account.id }).then(({ data: res }) => {
        this.accountListLoading = false
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        // this.setPoperModel(res.data)
        this.accountData = res.data
      }).catch(() => { this.accountListLoading = false })
    },
    handleNodeClick (node, data) {
      // this.$refs['newReportDataForm'].doClose()
      this.popVisibel = 'pop' + ++this.num
      this.visible = false
    },
    setPoperModel (data) {
      data.length > 0 && data.forEach(element => {
        this.$set(this.$data, 'pop' + element.id, false)
        if (element.children.length > 0) this.setPoperModel(element.children)
      })
    },
    limitNameLength (rule, value, callback) {
      if (value.length > 256) callback(new Error('Limit the name within 256 characters'))
      callback()
    },
    refreshTempList () {
      this.$emit('refreshTemp')
    },
    handleClose (done) {
      done()
    },
    searchInput (val) {
      this.$refs.treeIn.filter(val)
    },
    addGroupItemClose () {
      this.$refs['addAccount_item'].resetFields()
    },
    addAccountItemClose () {
      this.dataForm.name = ''
    },
    addAccountItemOpen (data) {
      this.dataForm.name = data.label
    },
    filterNode (value, data) {
      if (!value) return true
      return data.label && data.label.toLowerCase().indexOf(value.toLowerCase()) !== -1
    },
    callbackModel () {
      // this.$set(this.)
      return this.dataForm.name
    },
    editAccountGp (e, node, data) {
      e.stopPropagation()
    },
    setCurrNodeKey (key) {
      this.currKey = key
      this.$nextTick(function () {
        this.$refs.treeIn.setCurrentKey(key)
      })
    },
    checkTreeData (node) {
      // if()
    },
    addAccountGp (e) {
      e.stopPropagation()
    },
    deleteAccoutGp (e, item) {
      // e.stopPropagation()
      let params = {
        id: item ? item.id : '',
        accountId: this.account.id
      }
      this.$interface.mapping.deleteAccountItem(params).then(({ data: res }) => {
        this.addLoading = false
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.$message({
          type: 'success',
          message: 'success!'
        })
        this.refreshTempList()
        this.visible = false
        this.init()
      }).catch(() => { this.addLoading = false })
    },
    dataFormSubmitHandle (item, account) {
      let params = {
        label: this.dataForm.name,
        pid: item ? item.id : '',
        accountId: this.account.id,
        account: account ? 1 : 0
      }
      if (this.flag) {
        this.flag = false
        this.addLoading = true
        this.$refs['addAccount_item'].validate().then(() => {
          this.addTopNodeAccount(params)
        }).catch(() => { this.flag = true; this.addLoading = false })
      }
    },
    dataFormEditSubmitHandle (item, account) {
      let params = {
        label: this.dataForm.name,
        pid: item.id ? item.id : '',
        accountId: this.account.id,
        account: account ? 1 : 0
      }
      this.$refs['addAccount_item'].validate().then(() => {
        this.updateAccount(params, item.id)
      }).catch(() => { })
    },
    addTopNodeAccount (params) {
      this.$interface.mapping.addAccount(params).then(({ data: res }) => {
        this.addLoading = false
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.refreshTempList()
        this.visible = false
        this.init()
        this.flag = true
      }).catch(() => {
        this.addLoading = false
        this.flag = true
      })
    },
    updateAccount (params, id) {
      this.addLoading = true
      this.$interface.mapping.updateAccount(params, id).then(({ data: res }) => {
        this.addLoading = false
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.visible = false
        this.init()
      }).catch(() => { this.addLoading = false })
    },
    saveMappingItemAccount () {
      if (this.flag) {
        this.accountListLoading = true
        this.flag = false
        this.$interface.mapping.updateMappingItem({
          accountId: this.account.id,
          items: this.accountData
        }).then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.accountListLoading = false
          this.$message.success('Success')
          this.$emit('refreshTemp')
          this.flag = true
          this.dialogVisible = false
        }).catch(() => {
          this.flag = true
          this.accountListLoading = false
        })
      }
    },
    allowDropTreeLeft (draggingNode, dropNode) {
      if (draggingNode.data.pid === dropNode.data.pid) {
        return draggingNode
      } else {
        return false
      }
    },
    handleDragend (draggingNode, endNode, position, event) {
      if (draggingNode.data.pid === endNode.data.pid && draggingNode.data.id !== endNode.data.id) {
        this.$refs.treeIn.remove(draggingNode.data)
        this.$refs.treeIn.insertBefore(draggingNode.data, endNode)
      }

      event.stopPropagation()
    },
    append (data) {
      // const newChild = { id: id++, label: 'testtest', children: [] }
      // if (!data.children) {
      //   this.$set(data, 'children', [])
      // }
      // data.children.push(newChild)
    },

    remove (node, data) {
      // const parent = node.parent
      // const children = parent.data.children || parent.data
      // const index = children.findIndex(d => d.id === data.id)
      // children.splice(index, 1)
    }
  }
}
</script>
<style lang="scss">
.editAccount {
  .el-dialog__footer{
    padding: 10px;
    .el-button{
      padding: 8px 16px;
    }
  }
  .accounts_conditions {
    padding: 0 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 48px;
    box-shadow: 0px 1px 0px 0px #f0f0f0;
    margin-bottom: 1px;
    .el-input {
      width: 180px;
    }
    .conditions_ri {
      font-size: 14px;
      font-weight: 400;
      color: #138dc7;
      line-height: 20px;
      cursor: pointer;
      img {
        width: 14px;
        height: 14px;
        margin-right: 10px;
      }
    }
  }
  .el-dialog__headerbtn{
    top: 18px;
  }
  .accountTree {
    padding: 0 20px;
    overflow-y: auto;
    height: 50vh;
    .el-tree-node__content {
      height: 48px;
      box-shadow: 0px -1px 0px 0px #f0f0f0;
    }
    .el-tree-node__content:hover {
      background-color: transparent;
    }
    .el-icon-caret-right:before {
      content: "\E6E6";
      font-family: cuifont !important;
      font-size: 12px;
      font-style: normal;
      -webkit-font-smoothing: antialiased;
    }
    ::v-deep .el-tree-node__children {
      ::v-deep .treeitem {
        .el-tree-node__content {
          height: 48px;
          box-shadow: 0px -1px 0px 0px #f0f0f0;
        }
      }
    }
    .el-tree--highlight-current
      .el-tree-node.is-current
      > .el-tree-node__content {
      background-color: #f5f7fa !important;
    }
    .el-tree--highlight-current
      .el-tree-node.is-current
      > .el-tree-node__content
      > .custom-tree-node
      > .item_tree_btn_group {
      // background-color: #F5F7FA !important;
      display: flex !important;
    }
  }
  .custom-tree-node:hover .item_tree_btn_group {
    display: flex;
  }
  // .is-current .item_tree_btn_group{
  //   display: block  !important;
  // }
  .el-tree-node:focus
    > .el-tree-node__content
    > .custom-tree-node
    > .item_tree_btn_group {
    display: flex !important;
  }
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
    height: 100%;
    margin-left: 10px;
    .item_tree_btn_group {
      display: none;
    }
    .accounts_btn {
      width: 28px;
      height: 28px;
      display: inline-block;
      background-size: 14px;
      background-position: center;
      background-repeat: no-repeat;
    }
    .edit_btn {
      margin-right: 10px;
      background-image: url("../../../../assets/mspbots/qa-bot/edit-bot-block.png");
    }
    .edit_btn:hover {
      background-image: url("../../../../assets/mspbots/mapping/action_edit.png");
    }
    .add_btn {
      margin-right: 10px;
      background-image: url("../../../../assets/mspbots/mapping/add_account.png");
    }
    .add_btn:hover {
      background-image: url("../../../../assets/mspbots/mapping/add-circle-plus.png");
    }
    .delete_btn {
      background-image: url("../../../../assets/mspbots/qa-bot/escalation_delete.png");
    }
    .delete_btn:hover {
      background-image: url("../../../../assets/mspbots/mapping/action_delete.png");
    }
    .accounts_btn:hover {
      background-color: #e6f7ff;
    }
  }
}
</style>
